package config

import (
	"encoding/json"
	"flag"
	log "github.com/cihub/seelog"
	"io/ioutil"
	"os"
	"tunnel/common/config/role"
)

var Current = Config{}

//
// Config
// @Description:
//
type Config struct {
	Global Global  `json:"global"`
	User   User    `json:"user"`
	Routes []Route `json:"route"`
	Device Device  `json:"device"`
	Auth   Auth    `json:"auth"`
}

//
// Global
// @Description: global config
//
type Global struct {
	Tunnel
	Role    role.Name `json:"role"`
	MTU     int       `json:"mtu"`
	Pprof   int       `json:"pprof"`
	Restart bool      `json:"restart"`
}

//
// readFromFile
// @Description:
// @receiver cfg
// @param path
//
func (cfg *Config) readFromFile(path string) {
	if path == "" {
		_ = log.Error("config not specific")
		os.Exit(-1)
		return
	}
	log.Info("load config from : ", path)
	file, err := os.OpenFile(path, os.O_RDONLY, 0600)
	defer func(file *os.File) {
		_ = file.Close()
	}(file)
	if err != nil {
		_ = log.Error("failed to open config file : " + err.Error())
		os.Exit(-1)
	}
	bytes, err := ioutil.ReadAll(file)
	if err != nil {
		_ = log.Error("failed to read config file : " + err.Error())
		os.Exit(-1)
	}
	_ = json.Unmarshal(bytes, cfg)
}

//
// Load
// @Description:
//
func Load() {
	c := flag.String("c", "", "config path")
	flag.Parse()
	Current.readFromFile(*c)
}
